package com.reindeer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reindeer.dto.LoginDTO;
import com.reindeer.entity.SysUser;
import com.reindeer.mapper.SysUserMapper;
import com.reindeer.service.SysUserService;
import com.reindeer.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserVO login(LoginDTO loginDTO) {
        // 1. 根据用户名查询
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, loginDTO.getUsername());
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        
        if (user == null) {

            throw new RuntimeException("用户名或密码错误");
        }
        
        // 2. 密码比对
//        String password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (!loginDTO.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 3. 判断用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("账号已禁用");
        }
        
        // 4. 转换为VO对象并返回
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
} 